package com.dchh.android.suverynew.act;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dchh.android.suverynew.R;
import com.dchh.android.suverynew.adapter.LevelSelectAdapter;
import com.dchh.android.suverynew.base.SBaseActivity;
import com.dchh.android.suverynew.common.SPreferencesManager;
import com.dchh.android.suverynew.views.OperatePopupWindow;
import com.dhcc.android.base.base.MSApplication;
import com.dhcc.android.base.db.DBImportUtil;
import com.dhcc.android.base.db.DBManagerUtil;
import com.dhcc.android.base.gis.SelectItemChangedListener;
import com.dhcc.android.base.gis.TouchLongToolCommen;
import com.dhcc.android.base.utils.CommenUtil;
import com.dhcc.android.base.utils.Constants;
import com.dhcc.android.base.utils.DKMapUtil;
import com.dhcc.android.base.utils.FileUtil;
import com.dhcc.android.base.utils.StringUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import srs.Display.Symbol.TextSymbol;
import srs.Geometry.Envelope;
import srs.Geometry.FormatConvert;
import srs.Geometry.IEnvelope;
import srs.Geometry.IGeometry;
import srs.Geometry.IPoint;
import srs.Layer.CommonLayer;
import srs.Rendering.CommonRenderer;
import srs.Utility.sRSException;
import srs.tools.MapControl;

/**
 * @author zhoudan
 * @date 2016年4月6日
 */
public class SGSCDKSelectActivity extends SBaseActivity {
    /**
     * 层级目录
     */
    private TextView title;//
    /**
     * 层级选择目录布局
     */
    private LinearLayout titleLayout;
    /**
     * 地图布局
     */
    private LinearLayout selectListLayout;
    private ListView selectListview;
    private TextView selectClose;

    /**
     * 指南针
     */
    private LinearLayout zhinanzhen;


    /**
     * 任务名称
     */
    private String taskName;
    /**
     * 空间信息全局变量
     */
    public final static String GEO = "GEO";
    private MapControl dkSelectMapControl;

    // 选择列表的数据
    /**
     * 层级列表格式化数据
     */
    private List<Map<String, String>> levelList = new ArrayList<Map<String, String>>();
    /**
     * 原始数据
     */
    private List<Map<String, String>> dataList = null;
    private LevelSelectAdapter adapter;
    /**
     * 数据库管理工具
     */
    public static DBManagerUtil dBManagerUtil;
    /**
     * 样方编号主键
     */
    public static String YFBHU = "";
    public static String surveyDKIDPath;
    /**
     * 任务包路径
     */
    public static String root;
    /**
     * 路径
     */
    private String navtitle;
    /**
     * 路径
     */
    private String yfbh;
    /**
     * 地块工具类
     */
    DKMapUtil dkMapUtil;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dk_level_select);
    }

    OnClickListener viewClick = new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.common_nav) {
                selectListLayout.setVisibility(View.VISIBLE);
            } else if (v.getId() == R.id.close) {
                selectListLayout.setVisibility(View.GONE);
            }
        }
    };

    private void getView() {
        // 获取视图组件
        title = (TextView) findViewById(R.id.common_title);
        title.setText(navtitle);
        titleLayout = (LinearLayout) findViewById(R.id.common_nav);
        selectListLayout = (LinearLayout) findViewById(R.id.select_list_layout);
        selectListview = (ListView) findViewById(R.id.select_listview);
        selectClose = (TextView) findViewById(R.id.close);

        RelativeLayout.LayoutParams rl = new RelativeLayout.LayoutParams(Constants.screenWidth / 3,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
        rl.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        rl.leftMargin = 10;
        selectListLayout.setLayoutParams(rl);
        // 设置列表点选监听
        selectListview.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
                // 改变选中item的样式
                adapter.setSelect(position);
                adapter.notifyDataSetChanged();
                itemSelected(position, false);
            }
        });

        if (adapter == null) {
            adapter = new LevelSelectAdapter(this, levelList);
            selectListview.setAdapter(adapter);
        }
        selectListLayout.setVisibility(View.GONE);

        titleLayout.setOnClickListener(viewClick);
        selectClose.setOnClickListener(viewClick);

        zhinanzhen = (LinearLayout) findViewById(R.id.zhinanzhen_operate);
        zhinanzhen.setVisibility(View.VISIBLE);
        zhinanzhen.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(SGSCDKSelectActivity.this, CompassActivity.class);
                startActivity(intent);
            }
        });
    }

    /**
     * 列表或者地图点选
     *
     * @param position 选中的item索引
     * @param isMap    是否为地图点选
     */
    public void itemSelected(final int position, boolean isMap) {
        // 地图自动缩放
        zoomInDKView(position);
        final Map<String, String> map = dataList.get(position);
        Constants.select = dataList.get(position);
        //显示操作窗
        final OperatePopupWindow opw = new OperatePopupWindow(this);
        opw.show(titleLayout, "实割实测填报", new OnClickListener() {

            @Override
            public void onClick(View v) {
                opw.dismiss();
                // 获取当前范围自然地块的图片
                Constants.ZRDKBITMAP = dkSelectMapControl.getBitmap();
                Intent intent = new Intent(SGSCDKSelectActivity.this, SGSCReportActivity.class);
                intent.putExtra("taskName", taskName);
                intent.putExtra("DKBHU", map.get("DKBHU"));
                intent.putExtra("YFBHU", map.get("YFBHU"));
                startActivity(intent);
                overridePendingTransition(R.anim.push_right_in, R.anim.push_left_out);
            }
        });

    }


    /**
     * 图层放大 add by duanwg
     *
     * @param index 所选的图层的顺序号
     */
    public void zoomInDKView(int index) {

        DBImportUtil.openDatabase(root, Constants.currentTask.getTitle(), "/TASK/TRANSPORT/DATA.db");
        String table = "样方自然地块" + Constants.currentTask.getRefrence();

        String[] str = {"GEO", "YFDKBH"};
        final List<Map<String, String>> entityList = DBImportUtil.listData(table, str, "", "", "YFBHU='" + YFBHU + "'");
        Constants.displayLableNames.clear();
        if (entityList != null && entityList.size() != 0) {// 查出为[{GEO=null},{GEO=null}]
            boolean isFirst = true;
            try {
                for (Map<String, String> map : entityList) {
                    String wkt = map.get("GEO");

                    if (StringUtil.isNotEmpty(wkt)) {
                        IGeometry geo = FormatConvert.WKTToPolygon(wkt);
                        if (geo != null) {
                            if (isFirst) {// 有数据后 第一次进来的时候 将清空
                                isFirst = false;
                                Constants.geometrys.clear();
                            }
                            Constants.geometrys.add(geo);
                        }
                    }
                    String LableID = "";
                    LableID = map.get("YFDKBH");

                    if (LableID != null) {
                        Constants.displayLableNames.add(LableID);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        Constants.COMMONLAYER.setInitInfos("TableName", Constants.geometrys, null,
                srs.Geometry.srsGeometryType.Polygon, Constants.displayLableNames, new Envelope(), null);
        ((CommonRenderer) Constants.COMMONLAYER.getRenderer()).setSymbol(Constants.SYMBOLCBJ);
        // 地图控件
        IEnvelope env = Constants.COMMONLAYER.getGeometry(index).Extent();
        env = new Envelope(env.XMin() - env.Width() / 10, env.YMin() - env.Height() / 10,
                env.XMax() + env.Width() / 10, env.YMax() + env.Height() / 10);
        dkSelectMapControl.getActiveView().FocusMap().setExtent(env);

        // 高亮显示
        IPoint centerPoint = null;
        try {
            if (CommenUtil.IsListSelected) {
                centerPoint = Constants.COMMONLAYER.getGeometry(index).CenterPoint();
            } else {
                centerPoint = Constants.TargetPointTouch;
            }
            CommenUtil.setLightSelected(Constants.COMMONLAYER, index, (MapControl) CommenUtil.getMapControl(),
                    centerPoint);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 刷新图层
        dkSelectMapControl.Refresh();

    }


    private void mapView() {
        getData();
        // 刷新列表数据
        adapter.setSelect(-1);
        adapter.refresh(levelList);

        // 计算geometrys
        DBImportUtil.openDatabase(root, Constants.currentTask.getTitle(), "/TASK/TRANSPORT/DATA.db");
        String table = "样方自然地块" + Constants.currentTask.getRefrence();

        String[] str = {"GEO", "YFDKBH"};
        final List<Map<String, String>> entityList = DBImportUtil.listData(table, str, "", "", "YFBHU='" + YFBHU + "'");
        Constants.displayLableNames.clear();
        if (entityList != null && entityList.size() != 0) {// 查出为[{GEO=null},{GEO=null}]
            boolean isFirst = true;
            try {
                for (Map<String, String> map : entityList) {
                    String wkt = map.get("GEO");

                    if (StringUtil.isNotEmpty(wkt)) {
                        IGeometry geo = FormatConvert.WKTToPolygon(wkt);
                        if (geo != null) {
                            if (isFirst) {// 有数据后 第一次进来的时候 将清空
                                isFirst = false;
                                Constants.geometrys.clear();
                            }
                            Constants.geometrys.add(geo);
                        }
                    }
                    String LableID = "";
                    LableID = map.get("YFDKBH");

                    if (LableID != null) {
                        Constants.displayLableNames.add(LableID);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Constants.COMMONLAYER.setLabelSymbol(new TextSymbol(Typeface.create("Times New Roman", Typeface.NORMAL), 0,
                18f, false, Color.YELLOW));

        Constants.COMMONLAYER.setInitInfos("TableName", Constants.geometrys, null,
                srs.Geometry.srsGeometryType.Polygon, Constants.displayLableNames, new Envelope(), null);
        ((CommonRenderer) Constants.COMMONLAYER.getRenderer()).setSymbol(Constants.SYMBOLCBJ);
        // 地图控件
        IEnvelope env = CommenUtil.getMap().getExtent();
        dkSelectMapControl = (MapControl) findViewById(R.id.mapmain);

        dkSelectMapControl.getActiveView().FocusMap(CommenUtil.getMap());
        CommenUtil.getMap().setExtent(env);

        CommenUtil.getMap().setDeviceExtent(
                new Envelope(0, 0, dkSelectMapControl.getWidth(), dkSelectMapControl.getHeight()));
        // 刷新图层
        dkSelectMapControl.Refresh();

        /** 增加地图点选事件 */
        /** CommenLayer的点击事件 */
        TouchLongToolCommen touchLongTool = new TouchLongToolCommen(Constants.COMMONLAYER);
        dkSelectMapControl.ClearDrawTool();
        touchLongTool.setBuddyControl(dkSelectMapControl);// mapControl为操作的地图控件
        touchLongTool.onClick(dkSelectMapControl);
        touchLongTool.setEnable(true);
        // 设置不累计选择项目
        touchLongTool.IsOnlyOneTime = false;
        // 设置是不为单选
        touchLongTool.IsOnlyOneSelect = false;
        // 设置选中或未选中条目时，触发的事件
        touchLongTool.zoom2Selected = new SelectItemChangedListener() {

            @Override
            public void doEventSettingsChanged(Object tar) {
                Integer index = (Integer) tar;
                System.out.println("####点选的自然地块顺序号：" + index);

                adapter.setSelect(index);
                adapter.notifyDataSetChanged();
                itemSelected(index, true);
            }
        };
        dkSelectMapControl.setDrawTool(touchLongTool);
    }

    private void getData() {
        String pfield = "YFBHU";
        // 获取数据库中当前层级的下级数据列表
        String[] fields = {"DKBHU", "YFDKBH", "YFBHU", "TBLXMC", "CUNMC", "CUNDM", "rowid", "GEO"};
        try {
            DBImportUtil.openDatabase(root, Constants.currentTask.getTitle(), "/TASK/TRANSPORT/DATA.db");
            String tablename = "样方自然地块" + Constants.currentTask.getRefrence();
            if (YFBHU == null) {
                dataList = DBImportUtil.listData(tablename, fields, null, null);
            } else {
                dataList = DBImportUtil.listData(tablename, fields, pfield, YFBHU);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "操作外部数据库出错", Toast.LENGTH_SHORT).show();
        }

//        setTitleName("样方" + yfbh + "的自然地块 ("+dataList.size()+")");

        // 格式化原始数据
        levelList.removeAll(levelList);
        for (Map<String, String> map : dataList) {
            Map<String, String> m = new HashMap<String, String>();
            m.put("id", map.get("DKBHU"));
            String v = map.get("YFDKBH");
            m.put("name", v);

            levelList.add(m);
        }
    }

    private void goBack() {
        if (StringUtil.isFastDoubleClick(500)) {
            return;
        }
        try {
            CommenUtil.getMap().getElementContainer().ClearElement();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            // 从map 中删除commonLayer
            if (Constants.COMMONLAYER.getName() != null) {
                CommenUtil.getMap().RemoveLayer(Constants.COMMONLAYER);
            }

        } catch (sRSException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        finish();
        overridePendingTransition(R.anim.push_left_in, R.anim.push_right_out);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (Constants.data_refresh) {
            Constants.data_refresh = false;
            getData();
            adapter.refresh(levelList);
        }
    }

    @Override
    protected void setTitle(TextView toolbar_title) {

    }

    @Override
    protected void initView() {
        root = SPreferencesManager.getValue(MSApplication.TASK_SAVE_PATH, FileUtil.getSavePath());
        surveyDKIDPath = root + "/" + Constants.currentTask.getTitle() + "/TASK/TRANSPORT/DATA.db";
        // 等价于YFBHU
        YFBHU = getIntent().getStringExtra("pvalue");
        navtitle = getIntent().getStringExtra("navtitle");
        // 样方编号，对应下拉列表的下标
        yfbh = getIntent().getStringExtra("yfbh");
        taskName = getIntent().getStringExtra("taskName");

        setTitle("样方" + yfbh + "的自然地块");
        // // 初始化CommonLayer
        Constants.COMMONLAYER = new CommonLayer();
        try {
            CommenUtil.getMap().AddLayer(Constants.COMMONLAYER);
        } catch (IOException e) {
            e.printStackTrace();
        }
        getView();
        mapView();
        dBManagerUtil = DBManagerUtil.getInstance(surveyDKIDPath, SGSCDKSelectActivity.this);
        dkMapUtil = new DKMapUtil(this, dBManagerUtil, Constants.select, dkSelectMapControl);
        StringUtil.dismissDialog(Constants.DIALOG);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.sgscdk_select_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent intent;
        switch (item.getItemId()) {
            case R.id.zuowu:
                intent = new Intent(SGSCDKSelectActivity.this, ZWPhotoActivity.class);
                intent.putExtra("type", 0);
                intent.putExtra("yfbh", yfbh);
                startActivity(intent);
                break;
            case R.id.tuzhi:
                intent = new Intent(SGSCDKSelectActivity.this, ZWPhotoActivity.class);
                intent.putExtra("type", 3);
                intent.putExtra("yfbh", yfbh);
                startActivity(intent);
                break;
        }
        return true;
    }
}
